package com.lizeng.manage.permission;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import com.fd.dao.base.common.Condition;
import com.fd.dao.base.common.Operators;
import com.fd.util.MyUtils;
import com.lizeng.manage.pojo.JuriGroup;
import com.lizeng.manage.pojo.Jurisdiction;
import com.lizeng.manage.pojo.PermissionGroups;
import com.lizeng.manage.pojo.UserGroup;
import com.lizeng.manage.pojo.Users;
import com.lizeng.manage.service.IPermissionService;
import com.lizeng.manage.utils.ManageUtils;

/**
 * 权限注解解析处理器
 * 
 * @author 符冬
 * 
 */
@Component
public final class PermissionsHandler {

	@Resource
	private IPermissionService permissionService;

	private static String basepath = ManageUtils.INIT_RB.getString(
			"permission.path").replace('.', File.separatorChar);

	@SuppressWarnings("unchecked")
	@PostConstruct
	public void init() {
		URL ul = this.getClass().getResource("/" + basepath);
		File file = new File(ul.getFile());
		List<String> list = new ArrayList<String>();
		getClassNames(file, list);
		List<Jurisdiction> jds = permissionService.getJurisdictionDao()
				.getList();
		List<Jurisdiction> njds = new ArrayList<Jurisdiction>();
		for (String s : list) {
			try {
				@SuppressWarnings("rawtypes")
				Class clazz = getClass().getClassLoader().loadClass(
						s.replace(File.separatorChar, '.'));
				if (clazz.isAnnotationPresent(Controller.class)) {
					Method[] mds = clazz.getMethods();
					for (Method m : mds) {
						if (m.isAnnotationPresent(Permissions.class)) {
							Permissions p = m.getAnnotation(Permissions.class);
							Jurisdiction jurisdiction = new Jurisdiction();
							jurisdiction.setModuleValue(p.module());
							jurisdiction.setActionName(p.info());
							jurisdiction.setActionValue(p.value());
							if (!jds.contains(jurisdiction)
									&& !njds.contains(jurisdiction)) {
								njds.add(jurisdiction);
							}
						}
					}
				}

			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
		}
		/***
		 * 1、权限保存
		 */
		permissionService.saveJurisdictions(njds);

		/***
		 * 2、系统用户加载
		 */
		Users user = permissionService.getUsersDao().get(
				MyUtils.getConditions(new Condition("isSuper", Operators.EQ,
						true)), "sid");
		if (user == null) {
			String userName = ManageUtils.INIT_RB.getString("sysUser");
			String userPwd = ManageUtils.INIT_RB.getString("userPwd");
			if (MyUtils.isNotEmpty(userPwd) && MyUtils.isNotEmpty(userName)) {
				user = new Users();
				user.setIsSuper(true);
				user.setIsVisible(true);
				user.setUserName(userName.trim());
				user.setUserPwd(userPwd.trim());
				user = permissionService.persistUser(user);
			} else {
				throw new RuntimeException("超级用户名没有设置");
			}

		}
		/***
		 * 系统权限组创建
		 */
		PermissionGroups pg = permissionService.getPermissionGroupsDao().get(
				MyUtils.getConditions(new Condition("isSuper", Operators.EQ,
						true)), "groupId");
		if (pg == null) {
			pg = new PermissionGroups();
			pg.setGroupName("超级权限组");
			pg.setIsSuper(true);
			pg = permissionService.persistPermissionGroup(pg);
		}
		/**
		 * 权限组关联权限
		 */
		List<Jurisdiction> jdts = permissionService.getJurisdictionDao()
				.getListBySgCd(null, "actionValue");
		List<JuriGroup> jgs = permissionService.getJuriGroupDao()
				.getListByCondition(
						MyUtils.getConditions(new Condition("groupId",
								Operators.EQ, pg.getGroupId())));
		for (Jurisdiction jd : jdts) {
			JuriGroup jg = new JuriGroup();
			jg.setActionValue(jd.getActionValue());
			jg.setGroupId(pg.getGroupId());
			if (jgs.contains(jg)) {
				jgs.remove(jg);
			} else {
				jgs.add(jg);
			}
		}
		permissionService.saveJuriGroups(jgs);

		/***
		 * 超级用户授权
		 */
		UserGroup ug = permissionService.getUserGroupDao()
				.get(MyUtils.getConditions(new Condition("groupId",
						Operators.EQ, pg.getGroupId()), new Condition("userId",
						Operators.EQ, user.getSid())));
		if (ug == null) {
			ug = new UserGroup();
			ug.setGroupId(pg.getGroupId());
			ug.setUserId(user.getSid());
			permissionService.saveUserGroup(ug);
		}

	}

	// 扫描类名
	private static void getClassNames(File f, List<String> list) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (File sf : files) {
				if (sf.isDirectory()) {
					getClassNames(sf, list);
				} else {
					addlist(list, sf);
				}
			}

		} else {
			addlist(list, f);
		}
	}

	private static void addlist(List<String> list, File sf) {
		String name = getClassName(sf.getPath());
		if (name != null) {
			list.add(name.substring(0, name.lastIndexOf(".")));
		}
	}

	private static String getClassName(String path) {
		return path.substring(path.indexOf(basepath));
	}

}
